package edu.cth.speedapp.teacher;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import edu.cth.speedapp.asynctasks.*;
import edu.cth.speedapp.DeviceUuidFactory;
import edu.cth.speedapp.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class HelpQueueActivity extends Activity implements OnItemClickListener, ITaskCallback {
	private String roomName;
	private Timer timer;

	ArrayAdapter<Student> adapter;
	ArrayList<Student> queueList;
	ListView listView;
	String deviceUuid;
	Activity hqa;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        setContentView(R.layout.teacher_help);

		hqa = this;
		
        Bundle extras = getIntent().getExtras();
    	queueList = new ArrayList<Student>();
    	
    	DeviceUuidFactory f = new DeviceUuidFactory(this);
    	deviceUuid = f.getDeviceUuid().toString();
        
        
		try{   		
    		roomName = extras.getString("roomName"); 
    		setTitle(roomName + "  (?)");   		
		} catch (Exception e) {
			//TODO Stuff.
			roomName = "Room";
		}
	//	updateList();
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
			getMenuInflater().inflate(R.menu.mode_menue, menu);
			return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()){
			case (R.id.helpButton):
				Toast.makeText(this, "Already in this mode. ", Toast.LENGTH_SHORT).show();
				break;
			case (R.id.tempoButton):


				new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/changeRoomMode.php?roomID=" + roomName + "&&mode=tempo");
			
				
				Intent i = new Intent(this, TeacherInRoomActivity.class);
				i.putExtra("roomName", roomName);
				startActivity(i);
				this.finish();
				break;
			case R.id.leaveRoomButton:
				onClickLeaveRoom();
			break;
			case R.id.linkTagButton:
				onClickScanCode();
			break;
		
		}
		return super.onMenuItemSelected(featureId, item);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Log.d("tag", "Item clicked: " + arg1.getId());
	}

	private void updateList(){
		Log.d("tag", "UpdateList win");
		HTTPAsyncTask asyncTask =  new HTTPAsyncTask(this);
		String request = getString(R.string.baseURL) + "/getHelpQueue.php?roomID=" + roomName;
		asyncTask.execute(request);	
	}

	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	updateList();
        }
	};
	
	
	 @Override
	 protected void onResume() {
	  timer = new Timer();
	  try{
	  		timer.schedule(update, 0, 5000);
	  }
	  		catch(IllegalStateException e){
	  }
	  super.onResume();
	 }
	 @Override
	 protected void onPause() {
	  super.onPause();
	  timer.cancel();
	        timer.purge();
	        timer = null;
	 }

	 TimerTask update = new TimerTask(){

			@Override
			public void run() {
				handler.sendEmptyMessage(0);
				
			}
			
			
		};
	 
	public void httpTaskCallback(String results) {
		//TODO update lsit with new data.
		if(results == null) {
			Log.d("tag", "Problem with internet connection.");
			return;
		}
		

		Toast.makeText(this, "Call Back: " + results, Toast.LENGTH_SHORT).show();
		
		if(results.startsWith("Error")){
			//
		} else if (results.startsWith("Successfully deleted")){
			//
		} else if (results.startsWith("<br />")){
			//
		} else {
			
			int i = 0;
			Scanner scanner = new Scanner(results);
			queueList.clear();
			i++;
			String lid = null, lname = null, lmessage = null, ltimestamp = null;
			
			// The result is studentID, studentName, message, timestamp
			while(scanner.hasNextLine()){
				if(scanner.hasNextLine()){
					lid = scanner.nextLine();
				}
				if(scanner.hasNextLine()){
					lname = scanner.nextLine();
				}
				if(scanner.hasNextLine()){
					lmessage = scanner.nextLine();
				}
				if(scanner.hasNextLine()){
					ltimestamp = scanner.nextLine();
				}
				
				
				queueList.add(new Student(i, lid, lname, lmessage, ltimestamp));
				i ++;
			}
			
        	setTitle(roomName + "  (" + queueList.size() + ")");
    		
    		adapter = new ArrayAdapter<HelpQueueActivity.Student>(hqa, R.layout.simple_list_item, R.id.listText,  queueList);
    			
    		listView = (ListView) hqa.findViewById(R.id.listView1);
    		
    		if(listView != null){
    			listView.setAdapter(adapter);
    			listView.setOnItemClickListener((OnItemClickListener) hqa); 
    		}
		}
		
	}

	public void onClickCheckBox(View v){
		// Best way of dong this!
		v.getId();
		CheckBox c = (CheckBox) v;
		ViewGroup vg = (ViewGroup) c.getParent();
		TextView t = (TextView) vg.getChildAt(0);
		
		String s = (String) t.getText();
		Scanner sc = new Scanner(s);
		
		
		int i = -1;
		if(sc.hasNextInt()) {
			i = sc.nextInt();
			Log.d("INDEX: ", "" + i);
			i--;

		}
		
		Student st = null;
		try {
			st = queueList.get(i);	
		} catch (IndexOutOfBoundsException e) {
			
		}
		
		Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
		
		new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/removeFromHelpQueue.php?studentID=" + st.getID());
		
		return;
	}

	
	
	public void onClickLeaveRoom(){
        // Try to join the room
		new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/destroyRoom.php?roomID=" + roomName + "&&androidID=" + deviceUuid);
        
        // Close
        finish();
    }
	
	public void onClickScanCode() {
		Log.d("tag", "Scan code clicked.");
		Intent i = new Intent(this, TagLinkerActivity.class);
		i.putExtra("roomName", roomName);
		Log.d("tag", "Starting intent.");
		startActivity(i);
	}
	
	
	private class Student{
		
		String name;
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getI() {
			return i;
		}

		public void setI(int i) {
			this.i = i;
		}

		public String getMessage() {
			return message;
		}
		
		public String getTimestamp() {
			return timestamp;
		}
		
		public void setTimestamp(String time) {
			this.timestamp = time;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public String getID() {
			return ID;
		}

		public void setID(String iD) {
			ID = iD;
		}

		int i;
		String message;
		String ID;
		String timestamp;
		
		public Student(int i, String ID, String name, String message, String timestamp){
			this.i = i;
			this.ID = ID;
			this.name = name;
			this.message = message;
			this.timestamp = timestamp;
		}
		
		@Override
		public String toString() {
			return i + ": " + this.name + " - " + this.message + "\n" + timestamp;
		}
	}
	
}
